using System;
using System.Web;
using System.Web.UI;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Controls.Support;
using Sedna.Core.Controls.Support.Javascript;
using log4net;

namespace Sedna.Core.Controls
{

	public class JavascriptEmitter : BaseControl
	{
		private const string emitterKey="coreims.emitter";

		private static ILog log=LogManager.GetLogger(typeof(JavascriptEmitter));
		private JavascriptController controller;

		public static JavascriptEmitter Current
		{
			get
			{
				JavascriptEmitter emitter=HttpContext.Current.Items[emitterKey] as JavascriptEmitter;
				if (emitter!=null)
				{
					return emitter;
				}

				string errorMessage="Unable to locate JavascriptEmitter for current page. Put JavascriptEmitter control on your page.";
				log.Error(errorMessage);
				throw new ControllerConfigurationException(errorMessage);
			}	
		}

		public JavascriptController Controller
		{
			get { return controller; }
		}

		public JavascriptEmitter()
		{
			ConfigurationId="configuration.default.JavascriptEmitter";
			Context.Items[emitterKey]=this;
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			controller=new JavascriptController(Page, (IJavascriptEmitterConfiguration)Configuration);
		}

		protected override void Render(HtmlTextWriter writer)
		{
			writer.WriteLine("<!-- JavascriptEmitter -->");
			Controller.RenderObjects(writer);
		}

	}

}
